package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.SubAccountListBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.AddDeliveryInfoHistoryBean
import com.example.shushiyunsst.util.ADD_DELIVERY_INFO
import com.example.shushiyunsst.util.ADD_DELIVERY_INFO_HISTORY
import com.example.shushiyunsst.util.DELIVERY_INFO_HISTORY_BEAN
import com.example.shushiyunsst.util.startNavigation
import com.example.wallet.db.UserInfoManager
import ikidou.reflect.TypeBuilder
import kotlinx.android.synthetic.main.addde_livery_info_history_fragment.*
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.Type

@Route(path = ADD_DELIVERY_INFO_HISTORY)
class AddDeliveryInfoHistoryFragment : SimpleListFragment<AddDeliveryInfoHistoryBean>(),
    OnItemChildClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        delayedTime = 0
        isEnableLoadMore = false
        isAddDividerItemDecoration = false
    }

    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        mHeader.setBackgroundResource(R.color.bg_color_0)
        addHeader(R.layout.add_delivery_info_header_history)
//        addHeader(R.layout.comment_header_layout)

        mHeader.findViewById<View>(R.id.addAddressTv)
            .setOnClickListener {
                ARouter.getInstance()
                    .build(ADD_DELIVERY_INFO)
                    .startNavigation(this)
            }


        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "收货地址"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mAdapter.addChildClickViewIds(R.id.useIt, R.id.editor, R.id.deleteTv)
        mAdapter.setOnItemChildClickListener(this)
    }


    override fun getItemLayout(): Int {
        return R.layout.addde_livery_info_history_fragment
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: AddDeliveryInfoHistoryBean?) {
        helper?.setText(R.id.tile_tv, "${item?.recName}-${item?.recPhone}")
            ?.setText(R.id.tile_tv2, "${item?.recAddr}")
            ?.setViewSelect(R.id.defaultAv, item?.isDefault != 0)
            ?.setViewVisible(R.id.useIt, item?.isDefault == 0)
            ?.setViewVisible(R.id.okIcon, item?.isDefault != 0)
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(AddDeliveryInfoHistoryBean::class.java).endSubType().build()
    }

    override fun netRequest() {
//        val jsonFromRaw = ""
//        parseDate(jsonFromRaw)

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid)
        RestClient.builder()
            .url(R.string.queryMyAddrList)
            .raw(JSON.toJSONString(maps))
            .success {

                parseDate(it)

            }.failure {
                onFailed()
            }.error { _, _ ->
                onFailed()
            }
            .build()
            .post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val addrList = obj["addrList"]
        val array = JSON.parseArray(addrList.toString(), AddDeliveryInfoHistoryBean::class.java)
        loadListDate(array)
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
//        R.id.useIt,R.id.editor,R.id.deleteTv
        when (view.id) {
            R.id.useIt -> {
                useItem(item)
            }
            R.id.editor -> {
                ARouter.getInstance()
                    .build(ADD_DELIVERY_INFO)
                    .withSerializable(DELIVERY_INFO_HISTORY_BEAN, item)
                    .startNavigation(this)
            }
            R.id.deleteTv -> {

                val maps = mapOf(
                    "aid" to item?.aid,
                )

                RestClient.builder()
                    .url(R.string.deleteShopAddr)
                    .raw(JSON.toJSONString(maps))
                    .success {
                        mAdapter.removeAt(position)

                    }.failure {
                        Toast.makeText(_mActivity, R.string.sending_failed, Toast.LENGTH_SHORT)
                            .show()
                    }.error { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .build()
                    .post()
            }
        }
    }

    private fun useItem(item: AddDeliveryInfoHistoryBean?) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "aid" to item?.aid,
            "isDefault" to 1,
            "recAddr" to item?.recAddr,
            "recName" to item?.recName,
            "recPhone" to item?.recPhone,
            "areaIds" to item?.areaIds,
            "uid" to userInfo?.uid,
        )

        RestClient.builder()
            .url(R.string.updateShopAddr)
            .raw(JSON.toJSONString(maps))
            .success {

                EventBus.getDefault().post(MessageWrap.getInstance(ADD_DELIVERY_INFO))

            }.failure {
                Toast.makeText(_mActivity, R.string.sending_failed, Toast.LENGTH_SHORT)
                    .show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .build()
            .post()
    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)

        if (msg?.message == ADD_DELIVERY_INFO) {
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
            }
            onRefresh()
        }
    }
}